/* 
** Copyright (C) 2006  sejishikong <sejishikong@263.net>
** Authors:    sejishikong <sejishikong@263.net>
**             Wei Lian <lianwei3@gmail.com> 
** Maintainer: Wei Lian
**    This program is free software; you can redistribute it and/or modify
**    it under the terms of the GNU General Public License Version 2 as
**    published by the Free Software Foundation;
**
**    This program is distributed in the hope that it will be useful,
**    but WITHOUT ANY WARRANTY; without even the implied warranty of
**    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
**    GNU General Public License for more details.
**
**    You should have received a copy of the GNU General Public License
**    along with this program; if not, write to the Free Software
**    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
**
*/

#include "header.h"
#include "menubar.h"
#include "mainwindow.h"
#include "tabwidget.h"
#include "pageplay.h"
#include "mypopupmenu.h"
#include "config.h"
#include "fork.h"
#include "channel.h"
//#include "record.h"
//#include "timing.h"


MenuBar::MenuBar(QWidget * parent, const char *name):QMenuBar(parent,
							      name),
mainwindow(static_cast < MainWindow * >(parent))
{
    ///initialization
    QSettings settings;
    ///
    int id = 0;
    ///menu file
    menu_file = new QPopupMenu(this);
    menu_file->insertItem(tr("Exit"), qApp, SLOT(quit()), CTRL + Key_Q, 0);
    insertItem(tr("&File"), menu_file, id++);

    ///menu config
    menu_config = new QPopupMenu(this);
    menu_config->setCheckable(true);
    //channel color
    submenu_color = new QPopupMenu(this);
    submenu_color->setCheckable(true);
    submenu_color->insertItem(tr("User"), USER_COLUMN);
    submenu_color->insertItem(tr("Visit"), VISIT_COLUMN);
    submenu_color->insertItem(tr("Qs"), QS_COLUMN);
    submenu_color->insertItem(tr("Qc"), QC_COLUMN);
    submenu_color->insertItem(tr("Kbps"), KBPS_COLUMN);
    color_column =
	settings.readNumEntry("/qsopcast/ChannelColor", USER_COLUMN);
    submenu_color->setItemChecked(color_column, true);
    connect(submenu_color, SIGNAL(activated(int)), this,
	    SLOT(onSwitchColor(int)));
    menu_config->insertItem(tr("Channel Color"), submenu_color,
			    CHANNEL_COLOR);
    //show null channel
    menu_config->insertItem(tr("&Show Null Channel"), this,
			    SLOT(onNullChannelToggled()), CTRL + Key_N,
			    NULL_CHANNEL);
    menu_config->setItemChecked(NULL_CHANNEL,
				settings.
				readBoolEntry("/qsopcast/shownullchannels",
					      FALSE));
    //enabel channel sorting
    menu_config->insertItem(tr("&Enable Channel Sorting"), this,
			    SLOT(onChannelSortToggled()), CTRL + Key_S,
			    CHANNEL_SORT);
    menu_config->setItemChecked(CHANNEL_SORT,
				settings.
				readBoolEntry
				("/qsopcast/enablechannelsorting", FALSE));
    //configuration
    menu_config->insertItem(tr("&Config"), this, SLOT(onconfigclicked()),
			    CTRL + Key_F, CONFIG);
    insertItem(tr("&Config"), menu_config, id++);

    ///menu history
    history = new QPopupMenu(this);
    history->insertItem(tr("&Clear"), this, SLOT(clearHistory()),
			CTRL + Key_K, 0);
    history->insertSeparator();
    connect(history, SIGNAL(activated(int)), this,
	    SLOT(onChooseHistory(int)));
    insertItem(tr("&History"), history, id++);

    ///menu bookmark
    bookmark = new MyPopupMenu(this);
    bookmark->insertItem(tr("&Add"), this,
			 SLOT(addToBookmark()), CTRL + Key_B, 0);
    bookmark->insertSeparator();
    connect(bookmark, SIGNAL(activated(int)), this,
	    SLOT(onChooseBookmark(int)));
    insertItem(tr("&Bookmark"), bookmark, id++);

    ///menu help
    menu_help = new QPopupMenu(this);
    menu_help->insertItem(tr("&About"), this, SLOT(about()), CTRL + Key_H,
			  0);
    insertItem(tr("&Help"), menu_help, id++);

}


MenuBar::~MenuBar()
{
    QSettings settings;
    settings.writeEntry("/qsopcast/shownullchannels",
			menu_config->isItemChecked(NULL_CHANNEL));
    settings.writeEntry("/qsopcast/enablechannelsorting",
			menu_config->isItemChecked(CHANNEL_SORT));
    settings.writeEntry("/qsopcast/ChannelColor", color_column);

}


void MenuBar::clearHistory()
{
    for (int index = history->count() - 1; index >= 2; index--) {
	history->removeItemAt(index);
    }
}

void MenuBar::onSwitchColor(int id)
{
    mainwindow->channel->switchChannelColor(id);
    color_column = id;
    for (uint index = 0; index < submenu_color->count(); index++)
	submenu_color->setItemChecked(submenu_color->idAt(index), false);
    submenu_color->setItemChecked(id, true);
}


void MenuBar::onChannelSortToggled()
{
    menu_config->setItemChecked(CHANNEL_SORT,
				!menu_config->isItemChecked(CHANNEL_SORT));
    mainwindow->channel->toggleChannelSort();
}


void MenuBar::onNullChannelToggled()
{
    menu_config->setItemChecked(NULL_CHANNEL,
				!menu_config->isItemChecked(NULL_CHANNEL));
    mainwindow->channel->toggleNullChannel();
}


void MenuBar::onconfigclicked()
{
    mainwindow->vboxconfig->
	move(mapToGlobal
	     (QPoint
	      ((mainwindow->width() - mainwindow->vboxconfig->width()) / 2,
	       (mainwindow->height() -
		mainwindow->vboxconfig->height()) / 2)));
    mainwindow->vboxconfig->show();

}


void MenuBar::onChooseHistory(int id)
{
//    printf("history index=%d,id=%d\n", history->indexOf(id), id);
    if (id >= 2
	&& mainwindow->tabwidget->tabToolTip(mainwindow->tabwidget->
					     currentPage()) == "play") {
	QString str = history->text(id);
	QString name = str.mid(0,
			       str.find(mainwindow->vboxconfig->
					editchannelheader->text()) - 1);
	QString url =
	    str.mid(str.
		    find(mainwindow->vboxconfig->editchannelheader->
			 text()));
	QString type = url.mid(url.find(" ") + 1);
	url = url.mid(0, url.find(" "));
	//launch sop
	static_cast < PagePlay * >(mainwindow->tabwidget->currentPage())
	    ->fork->killSop();
	static_cast < PagePlay * >(mainwindow->tabwidget->currentPage())
	    ->fork->killPlayer();
	if (static_cast < PagePlay * >
	    (mainwindow->tabwidget->currentPage())
	    ->fork->forkSop(url, name, type) == TRUE) {
	} else
	    fprintf(stderr, "failed to launch sp-sc!\n");
    }
}


void MenuBar::onChooseBookmark(int id)
{
//    printf("bookmark index=%d,id=%d\n", bookmark->indexOf(id), id);
    if (id >= 2) {
	if (bookmark->rightbutton) {	///delete bookmark
	    bookmark->removeItem(id);
	} else if
	    (mainwindow->tabwidget->tabToolTip(mainwindow->tabwidget->
					       currentPage()) == "play") {
	    QString str = bookmark->text(id);
	    QString name = str.mid(0,
				   str.find(mainwindow->vboxconfig->
					    editchannelheader->text()) -
				   1);
	    QString url =
		str.mid(str.
			find(mainwindow->vboxconfig->editchannelheader->
			     text()));
	    QString type = url.mid(url.find(" ") + 1);
	    url = url.mid(0, url.find(" "));
	    //launch sop
	    static_cast < PagePlay * >
		(mainwindow->tabwidget->currentPage())
		->fork->killSop();
	    static_cast < PagePlay * >
		(mainwindow->tabwidget->currentPage())
		->fork->killPlayer();
	    if (static_cast < PagePlay * >
		(mainwindow->tabwidget->currentPage())
		->fork->forkSop(url, name, type) == TRUE) {
		///add to history
		addToPopupMenu(history, url, name, type);
	    } else
		fprintf(stderr, "failed to launch sp-sc!\n");

	}
    }
}


void MenuBar::addToPopupMenu(QPopupMenu * menu, QString url, QString name,
			     QString type)
{
    if (menu->count() == 2)	///no item
	menu->insertItem(name + " " + url + " " + type, 2);
    else if (menu->count() > 2) {
	bool flag = FALSE;
	uint index;
	for (index = 2; index < menu->count(); index++) {
	    QString str = menu->text(menu->idAt(index));
	    QString str_name = str.mid(0,
				       str.find(mainwindow->vboxconfig->
						editchannelheader->
						text()) - 1);
	    QString str_url =
		str.mid(str.
			find(mainwindow->vboxconfig->editchannelheader->
			     text()));
	    QString str_type = str_url.mid(str_url.find(" ") + 1);
	    str_url = str_url.mid(0, str_url.find(" "));

	    if (url == str_url) {
		if (name != str_name || type != str_type) {
		    menu->changeItem(menu->idAt(index),
				     name + " " + url + " " + type);
		}
		flag = TRUE;
		break;
	    }
	}
	if (flag == FALSE)
	    menu->insertItem(name + " " + url + " " + type,
			     menu->idAt(index - 1) + 1);
    } else
	fprintf(stderr, "err: count<2\n");
}


void MenuBar::addToBookmark()
{
    QListViewItem *item = mainwindow->channel->currentItem();
    if (item == 0)
	return;
    if (item->depth() == 1)
	addToPopupMenu(bookmark, item->text(URL_COLUMN),
		       item->text(NAME_COLUMN), item->text(STREAM_COLUMN));
}


#include "mozart.xpm"
void MenuBar::about()
{
    const QPixmap p1(mozart);
    QMessageBox m;
    m.setCaption("qsopcast");
    m.setIconPixmap(p1);
    m.setText(tr("qsopcast: a QT front-end to p2p TV sopcast.\n"
		 "(c)2005-2006 Liu Di. All rights reserved.\n"
		 "Maintainer: Wei Lian\n"
		 "Developers: Liu Di, Wei Lian\n"
		 "http://lianwei3.googlepages.com/home2"));
    m.exec();
}
